<template>
  <div class="tshirt-editor">
    <button @click="downloadCanvasAsPNG">Download Image</button>

    <canvas id="tshirtCanvas" width="600" height="600"></canvas>
  </div>
</template>

<script>
import { fabric } from 'fabric';
import huli from './huli.png'
import bg from './black.png'
import webp1 from './1.webp'

export default {
  name: 'TshirtEditor',
  mounted() {
    this.initializeCanvas();
  },
  methods: {
    initializeCanvas() {
      this.canvas = new fabric.Canvas('tshirtCanvas');

      fabric.Image.fromURL(webp1, (img) => {
        img.crossOrigin = 'Anonymous';
        img.scaleToWidth(600);
        img.scaleToHeight(600);
        img.set({
          left: 0,
          top: 0,
          selectable: false, // 使图片可拖拽
          hasControls: true, // 允许缩放、旋转控制
        });
        this.canvas.add(img);
        img.getElement().style.filter = 'brightness(0.1)';

        this.canvas.bringToFront(img);
        this.canvas.renderAll();
      },{ crossOrigin: 'Anonymous' });
            // 绘制一个简单的衣服图案（可以替换成真实的衣服图片）
            fabric.Image.fromURL('https://i.postimg.cc/0j4TL71b/1.png', (bgimg) => {
        console.log(bgimg);
        bgimg.crossOrigin = 'Anonymous';
        bgimg.scaleToWidth(150);
        bgimg.scaleToHeight(150);
        bgimg.set({
          left: 225,
          top: 220,
          selectable: true,
        });
        
        this.canvas.add(bgimg);
        // bgimg.getElement().style.filter = 'brightness(0.1)';
        bgimg.moveTo(0);
        this.canvas.on('object:moving', function(e) {
          bgimg.moveTo(0);
  });
        // this.canvas.setBackgroundImage(img, this.canvas.renderAll.bind(this.canvas));
      },{ crossOrigin: 'Anonymous' });

      const overlay = new fabric.Rect({
        left: 225,
        top: 220,
    width: 150,
    height: 150,
    fill: 'rgba(255, 255, 255, 0)', // 半透明白色
    selectable: false, // 不允许选中
    evented: false,   // 禁止响应事件
  });

  // 将遮罩层添加到 Canvas
  this.canvas.add(overlay);
    },
    downloadCanvasAsPNG() {
      const dataURL = this.canvas.toDataURL({
        format: 'png',  // 输出为 PNG 格式
        quality: 1,     // 设置图像质量
      });

      // 创建一个下载链接
      const link = document.createElement('a');
      link.href = dataURL;  // 设置链接指向合成图像
      link.download = 'tshirt-design.png';  // 设置下载的文件名

      // 模拟点击下载链接
      link.click();
    },
  },
};
</script>

<style scoped>
.tshirt-editor {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 100px;
}
canvas {
  border: 1px solid #000;
}
</style>
